package com.travel.server.manager.impl.command.question;

import com.travel.common.util.CollectionUtil;
import com.travel.server.manager.dto.request.PageRequest;
import com.travel.server.manager.dto.response.question.QueryQuestionListResponse;
import com.travel.server.manager.dto.response.question.QueryQuestionListResponse.QuestionItem;
import com.travel.server.manager.impl.command.AbstractCommand;
import com.travel.server.manager.impl.dal.PageDto;
import com.travel.server.manager.impl.dal.QuestionnaireDal;
import com.travel.server.manager.impl.dal.QuestionnaireDal.QuestionnaireParam;
import com.travel.server.manager.model.QuestionnaireInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018\11\15 0015 22:23
 * @Desc:
 */
@Component
@Slf4j
public class QueryQuestionListCommand extends AbstractCommand<PageRequest, QueryQuestionListResponse> {

    @Autowired
    private QuestionnaireDal questionnaireDal;

    @Override
    protected void checkInput(PageRequest request) {
        checkPageInput(request);
    }

    @Override
    public QueryQuestionListResponse handle(PageRequest request) {
        checkPageInput(request);

        QuestionnaireParam param = makeParam(request);
        PageDto<QuestionnaireInfo> pageDto = questionnaireDal.select(param);

        return makeResponse(pageDto);
    }

    private QueryQuestionListResponse makeResponse(PageDto<QuestionnaireInfo> pageDto){
        QueryQuestionListResponse response = new QueryQuestionListResponse();
        List<QuestionItem> questionList = new ArrayList<>();
        List<QuestionnaireInfo> list = pageDto.getList();
        if(!CollectionUtil.isEmpty(list)){
            for(QuestionnaireInfo questionnaireInfo : list){
                QuestionItem item = new QuestionItem();
                item.setCreateTime(questionnaireInfo.getCreateTime());
                item.setDescribe(questionnaireInfo.getQuestionnaireDescribe());
                item.setId(questionnaireInfo.getId());
                item.setName(questionnaireInfo.getQuestionnaireName());
                item.setTitle(questionnaireInfo.getQuestionnaireTitle());
                questionList.add(item);
            }
        }
        response.setTotalNum(pageDto.getTotal());
        response.setQuestionList(questionList);

        return response;
    }

    private QuestionnaireParam makeParam(PageRequest request){
        QuestionnaireParam param = new QuestionnaireParam();
        param.setOffset(request.getOffset());
        param.setLimit(request.getLimit());
        return param;
    }
}
